package com.cishu.orancle.common;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理
 * li
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // 通用异常处理
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<R<Object>> handleGeneralException(Exception e) {
        System.out.println("发生了一个异常: " + e);
        return new ResponseEntity<>(R.internalServerError(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理404异常
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public ResponseEntity<R<Object>> handleNotFound(NoHandlerFoundException e) {
        System.out.println("404 错误: " + e.getRequestURL());
        return new ResponseEntity<>(R.notFound("请求地址：" + e.getRequestURL() + " 不存在哦"), HttpStatus.NOT_FOUND);
    }

    // 处理SQL唯一键重复的异常
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public ResponseEntity<R<Object>> handleDuplicateKeyException(DuplicateKeyException e) {
        System.out.println("发生了一个唯一键重复的异常: " + e);
        return new ResponseEntity<>(R.internalServerError(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理自定义的异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<R<Object>> handleCustomException(CustomException e) {
        System.out.println("发生了一个自定义的异常: " + e);
        return new ResponseEntity<>(R.error(e.getMessage()), HttpStatus.BAD_REQUEST);
    }
}



